<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id="app"></div>


	<script type="text/javascript">

		/**
		 * 闭包
		 * 1、当内部函数被保存到外部时，将会生成闭包；
		 * 2、闭包会导致原有的作用域链不释放，造成内存泄露。
		 */
		
		
		// 累加器
		/*function add(){
			var num = 0;
			function a(){
				num ++;
				console.log(num);
			};
			return a;
		};
		var myAdd = add();
		myAdd();
		myAdd();*/

		// 1对多的闭包
		/*function test(){
			var num = 100;
			function a(){
				num ++;
				console.log(num);
			};
			function b(){
				num --;
				console.log(num);
			}
			return [a,b];
		}
		var myArr = test();
		myArr[0]();
		myArr[1]();*/


		// 闭包缓存
		/*function eater(){
			var food = "";
			var obj = {
				eat : function (){
					console.log("i am eating " + food);
					food = "";
				},
				push : function (myFood){
					food = myFood;
				}
			}
			return obj;
		}
		var eater = eater();
		eater.push('chenyouhu');
		eater.eat();*/

		/*function test(){
			var food = "apple";
			var obj = {
				eatFood : function(){
					if(food != ""){
						console.log("I am eating " + food);
						food = "";
					}else{
						console.log("There is nothing! empty!");
					}
				},
				pushFood : function(myFood){
					food = myFood;
				}
			}
			return obj;
		}
		var person = test();

		person.eatFood();
		person.eatFood();
		person.pushFood("banana");
		person.eatFood();*/


		// 闭包循环调用
		/*function test(){
			var arr = [];
			for(var i = 0; i < 10; i++){
				(function(j){
					arr[j] = function(){
						document.write(j + " ")
					}
				}(i));
			}
			return arr;
		}
		var myArr = test();
		for(var j = 0; j < 10; j++){
			myArr[j]();
		}*/









	</script>

</body>
</html>